from flask import Flask, session, redirect, url_for, escape, request, jsonify
import json


port = 2000
app = Flask(__name__)
app.debug = True
ALLOWED_ORIGINS = "*"
appHandlers={

}
def registHandler(category , method , handler):
    key = category+'/'+ method;
    appHandlers[key] = handler;
def getPs():
    return {}
@app.route("/rpc/<category>/<method>", methods=['GET', 'POST'])
def rpcHandler(category,  method):
    result ={
        "version":"rpc2023",
        "category":category,
        "method":method,
        "status":0,
        "datas":{},
        "error":{
            "code":-1,
            "message":""
        }
    }
    try:
        if request.method == 'OPTIONS':
            # 对于预检请求，我们发送带有正确CORS头信息的响应
            response = app.response_class()
            response.headers['Access-Control-Allow-Origin'] = ALLOWED_ORIGINS
            response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
            response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Cookie, Accept, Authorization, X-CSRF-TOKEN'
            response.headers['Access-Control-Expose-Headers'] = 'Origin, Content-Type, Cookie, Accept, Authorization, X-CSRF-TOKEN'
            response.headers['Access-Control-Max-Age'] = '86400'
            return response
        else:
            key = category+'/'+ method
            flag = key in  appHandlers.keys()
            if ( flag ):
                ps = getPs()
                handler = appHandlers[key]
                handler(ps , result , request )
            return jsonify(result) 
    except Exception as er:
        print(er)
        return jsonify(result) 
